package cn.com.spring.handler;


import cn.com.spring.annotation.Async;
import cn.com.utils.ThreadPoolUtils;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.concurrent.Callable;

/**
 * 生成异步代理
 *
 * @author LiuGuodong
 * @date 2023/01/28
 */
public class AsyncProxy implements MethodInterceptor {

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object result = null;
        Async annotation = method.getAnnotation(Async.class);
        //使用指定线程池
        if (annotation != null) {
            if (annotation.result()) {
                result = ThreadPoolUtils.submitTask(getCallable(o, objects, methodProxy), annotation.value());
            } else {
                ThreadPoolUtils.submitTask(getRunnable(o, objects, methodProxy));
            }
        } else {
            result = methodProxy.invokeSuper(o, objects);
        }
        return result;
    }

    /**
     * 获得可调用
     *
     * @param o           o
     * @param objects     物体
     * @param methodProxy 方法代理
     * @return {@link Callable}<{@link ?}>
     */
    private static Callable<?> getCallable(Object o, Object[] objects, MethodProxy methodProxy) {
        return () -> {
            try {
                return methodProxy.invokeSuper(o, objects);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        };
    }

    /**
     * 可运行
     *
     * @param o           o
     * @param objects     物体
     * @param methodProxy 方法代理
     * @return {@link Runnable}
     */
    private static Runnable getRunnable(Object o, Object[] objects, MethodProxy methodProxy) {
        return () -> {
            try {
                methodProxy.invokeSuper(o, objects);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        };
    }


}
